package com.phkj.qdh.utils

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * @ClassName:      recycleview绘制分割线
 * @Description:
 * @CreateDate:     2022/4/18 14:02
 */
class MyItemDecoration(
    private val color: Int?,
    private val width: Int = 2,
    private val orientation: Int
) : RecyclerView.ItemDecoration() {

    constructor(color: Int?) : this(color, 2, RecyclerView.VERTICAL)
    constructor(color: Int?,width:Int) : this(color, width, RecyclerView.VERTICAL)
    constructor(width:Int) : this(null, width, RecyclerView.VERTICAL)

    //创建画笔，设置放锯齿模式
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    init {
        if (color != null) {
            paint.color = color
        } else {
            paint.color = Color.TRANSPARENT
        }
        paint.style = Paint.Style.FILL
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        if (orientation == RecyclerView.VERTICAL) {
            outRect.set(0, 0, 0, width)
        } else {
            outRect.set(0, 0, width, 0)
        }

    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        if (orientation == RecyclerView.VERTICAL) {
            drawVertical(c, parent)
        } else {
            drawHorizontal(c, parent)
        }


    }

    private fun drawVertical(c: Canvas, rv: RecyclerView) {
        val left = rv.paddingLeft
        val right = rv.measuredWidth - rv.paddingRight
        val childSize = rv.childCount
        for (i in 0 until childSize) {
            val childView = rv.getChildAt(i)
            val layoutParams = childView.layoutParams as RecyclerView.LayoutParams
            val top = childView.bottom + layoutParams.bottomMargin
            val bottom = top + width.toFloat()
            c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)
        }
    }

    private fun drawHorizontal(c: Canvas, rv: RecyclerView) {
        val top = rv.paddingTop
        val bottom = rv.measuredHeight - rv.paddingBottom
        val childSize = rv.childCount
        for (i in 0 until childSize) {
            val childView = rv.getChildAt(i)
            val layoutParams = childView.layoutParams as RecyclerView.LayoutParams
            val left = childView.right + layoutParams.rightMargin
            val right = left + width
            c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)
        }

    }
}